package camid.services.nodemanager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class NextRelookup {
	
	private static final long LOOKUP_INTERVAL = 1000L;
	
	private long lastRelookupTime;

	public NextRelookup() {
		super();
		this.lastRelookupTime = System.currentTimeMillis();
	}
	
	public synchronized long nextRelookup() {
		long actualTime = System.currentTimeMillis();
		long diff = actualTime - lastRelookupTime;
		if(diff < LOOKUP_INTERVAL) {
			this.lastRelookupTime += LOOKUP_INTERVAL;
		} else {
			this.lastRelookupTime = actualTime;
		}
		return this.lastRelookupTime;
	}
	
	public static void main(String[] args) {
		final NextRelookup nextRelookup = new NextRelookup();
		final Set<Long> set = Collections.synchronizedSet(new TreeSet<Long>());
		final List<Future<?>> futSet = new ArrayList<Future<?>>();
		long initial = System.currentTimeMillis();
		ExecutorService executor = Executors.newCachedThreadPool();
		for(int i = 0; i < 100000; i++) {
			Future<?> fut = executor.submit(new Runnable() {

				@Override
				public void run() {
					long next = nextRelookup.nextRelookup();
					set.add(next);
				}
				
			});
			futSet.add(fut);
		}
		
		for(Future<?> fut : futSet) {
			try {
				fut.get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		for(Long val : set) {
			System.out.println(val);
		}
		long end = System.currentTimeMillis();
		System.out.println("Time Elapsed: " + (end - initial) + "ms.");
		
		executor.shutdown();
	}

}
